import { getCurrentUserId } from '@/utils/backend/auth'
import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url)
    const page = Number(searchParams.get('page')) || 1
    const pageSize = Number(searchParams.get('pageSize')) || 10
    const keyword = searchParams.get('keyword') || ''

    // 获取当前用户ID
    const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
    const currentUserId = await getCurrentUserId(token)

    // 构建查询条件
    const where = {
      AND: [
        // 排除当前用户
        { id: { not: currentUserId } },
        // 排除管理员
        { role: { not: 'admin' } },
        // 关键词搜索
        keyword
          ? {
              OR: [{ username: { contains: keyword } }, { nickname: { contains: keyword } }]
            }
          : {}
      ]
    }

    // 查询总数
    const total = await prisma.user.count({ where })

    // 查询用户列表
    const users = await prisma.user.findMany({
      where,
      skip: (page - 1) * pageSize,
      take: pageSize,
      orderBy: {
        createdAt: 'desc'
      }
    })

    return NextResponse.json({
      success: true,
      message: '获取成功',
      data: {
        list: users,
        pagination: {
          current: page,
          pageSize,
          total
        }
      }
    })
  } catch (error) {
    console.error('Get users failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '获取用户列表失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}

export async function POST(req: Request) {
  try {
    const data = await req.json()

    const user = await prisma.user.create({
      data: {
        ...data,
        password: '123456' // 默认密码
      }
    })

    return NextResponse.json({
      success: true,
      message: '创建成功',
      data: user
    })
  } catch (error) {
    console.error('Create user failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '创建用户失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}
